import { ref, computed, watch } from "vue";
import { defineStore } from "pinia";
import { uid, Notify, LocalStorage } from "quasar";
import type {
  entriesProps,
  updateEntryProps,
  entriesOptionsProps,
} from "./typing";
// pnpm install '@types/sortablejs'
import type { SortableEvent } from "sortablejs";
import { nextTick } from "process";

export const useEntriesStore = defineStore("entries-store", () => {
  /**
   * state
   */
  const entriesList = ref<entriesProps[]>([]);

  // 选项
  const options = ref<entriesOptionsProps>({
    sort: false,
  });

  watch(entriesList.value, () => saveEntriesList());

  /**
   * getters
   */

  // 计算总金额
  const totalAmount = computed(() => {
    return entriesList.value.reduce(
      (sum, item) => sum + (item.amount as number),
      0,
    );
  });

  // 计算已付费
  const totalAmountPaid = computed(() => {
    return entriesList.value.reduce((sum, item) => {
      return item.paid ? sum + (item.amount as number) : sum;
    }, 0);
  });

  // 运行费用
  const runningTotal = computed(() => {
    let runningTotal: number[] = [];
    let currentRunningTota = 0;

    if (entriesList.value.length) {
      entriesList.value.forEach((entry) => {
        let entryAmount = entry.amount ? entry.amount : 0;
        currentRunningTota = currentRunningTota + entryAmount;
        runningTotal.push(currentRunningTota);
      });
    }
    return runningTotal;
  });

  /**
   * actions
   */

  // 根据id查找条目
  const getEntryIndexById = (id: string) => {
    return entriesList.value.findIndex((e) => e.id === id);
  };

  // nextTick 解决排序后删除最后一项不成功问题
  const removeSlideItemIfExists = (id: string) => {
    nextTick(() => {
      const slideItem = document.querySelector(`#id-${id}`);
      if (slideItem) slideItem.remove();
    });
  };

  // 添加条目
  const addEntrie = (addEntryForm: entriesProps) => {
    // 必需使用{}, 保证是一个新对象
    const newEntry = Object.assign({}, addEntryForm, { id: uid() });
    entriesList.value.push(newEntry);
  };

  // 删除条目
  const deleteEntrie = (id: string) => {
    const index = getEntryIndexById(id);
    if (index !== -1) entriesList.value.splice(index, 1);
    // 修复：排序后，删除最后一项失效
    removeSlideItemIfExists(id);
    Notify.create({
      message: "删除成功",
      actions: [{ icon: "close", color: "white" }],
    });
  };

  // 更新条目名称/金额/
  const updateEntrie = (id: string, updates: updateEntryProps) => {
    const index = getEntryIndexById(id);
    if (index !== -1) {
      Object.assign(entriesList.value[index] as entriesProps, updates);
      Notify.create({
        message: "更新成功",
        actions: [{ icon: "close", color: "white" }],
      });
    }
  };

  // 本地存储
  const saveEntriesList = () => {
    LocalStorage.set("entriesList", entriesList.value);
  };
  // 加载存储
  const loadEntriesList = () => {
    const saveEntriesList = LocalStorage.getItem("entriesList");
    if (saveEntriesList) Object.assign(entriesList.value, saveEntriesList);
  };

  // 排序end
  /**
   * splice方法的使用：
   * - 第一个参数是要删除的元素的索引。
   * - 第二个参数是要删除的元素的数量。
   * - 第三个参数是要插入的新元素。
   */
  const sortEnd = (event: SortableEvent) => {
    if (event.oldIndex !== undefined && event.newIndex !== undefined) {
      const movedEntry = entriesList.value[event.oldIndex];
      // 如果oldIndex和newIndex相同，则不需要移动
      if (event.oldIndex === event.newIndex || !movedEntry) return;
      else {
        entriesList.value.splice(event.oldIndex, 1);
        entriesList.value.splice(event.newIndex, 0, movedEntry);
      }
    }
  };

  /**
   * return
   */
  return {
    // state
    entriesList,
    options,

    // getters
    totalAmount,
    totalAmountPaid,
    runningTotal,
    loadEntriesList,

    // actions
    addEntrie,
    deleteEntrie,
    updateEntrie,
    sortEnd,
  };
});
